﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;

namespace DigitalSolutionLibrary.Security
{
    public class HashMD5
    {
        private HashMD5()
        {
        }

        /// <summary>
        /// Hash a string to MD5 string
        /// </summary>
        /// <param name="strTohash"></param>
        /// <returns>String after hash</returns>
        public static string CreateMD5(string strTohash)
        {
            if (strTohash == null)
                return String.Empty;
            
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(strTohash);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2"));
            }
            return sb.ToString();
        }
    }
}
